const db = require('@/db/mysql');
const databaseConfig = require('$config/database.config');

/**
 * 公共服务
 */
class CommonService {
    /**
     * 设置行锁定
     * @param {*} tableName 表名
     * @param {*} colValue 字段值 
     * @param {string} [colName='id'] 字段名
     */
    async setRowLocked(tableName, colValue, colName = 'id') {
        try {
            // 如果是空状态，直接返回成功，不往下执行
            if (colValue === null || (Array.isArray(colValue) && colValue.length === 0)) {
                return true;
            }

            const COL_NAME = 'is_lock';
            const checkSQL = `
                SELECT COUNT(*) as count
                FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = '${databaseConfig.DATABASE}' 
                AND TABLE_NAME = '${tableName}' 
                AND COLUMN_NAME = '${COL_NAME}';
            `
            const checkResult = await db.query(checkSQL);
            // 如果字段不存在，则新增一个 is_lock 字段
            if (checkResult.code === 200 && checkResult.results.length > 0) {
                const isExist = checkResult.results[0].count === 1;
                // 不存在则需要创建这个字段
                if (!isExist) {
                    await db.query(`
                        ALTER TABLE ${tableName}
                        ADD COLUMN ${COL_NAME} TINYINT(1) COMMENT '是否锁定：1.是，0.否' DEFAULT 0;
                    `);
                }
            }
            const ids = typeof colValue === 'string' ? `'${colValue}'` : colValue.map(i => `'${i}'`).join(', ');
            const lockSQL = `UPDATE ${tableName} SET is_lock = 1 WHERE ${colName} IN (${ids})`;
            const lockResult = db.query(lockSQL);
            return lockResult.code === 200;
        } catch (error) {
            console.log(error);
            return false;
        }
    }

    /**
     * 检查行是否锁定
     * @param {*} tableName 表名 
     * @param {*} colValue 字段值
     * @param {*} colName 字段名
     * @returns {boolean}
     */
    async checkRowLocked(tableName, colValue, colName = 'id') {
        try {
            const SQL = `SELECT is_lock FROM ${tableName} WHERE ${colName} = '${colValue}' AND is_delete = 0`;
            const query = await db.query(SQL);
            if (query.code === 200 && query.results.length > 0) {
                if (query.results[0].is_lock === 1) {
                    return true;
                }
            }
            return false;
        } catch (error) {
            console.log("检查行是否锁定错误：", error);
            return false;
        }
    }

    /**
     * 设置行的用户信息
     * @param {*} param0 
     * @param {object} row 行数据
     * @param {string[]} fields 自定义字段
     * @param {string} created_key 创建用户key
     * @param {string} updated_key 更新用户key
     * @returns 
     */
    async setRowUser({ row, fields, created_key, updated_key }) {
        if (!row) return null;
        created_key = created_key || 'created_user';
        updated_key = updated_key || 'updated_user';
        const { created_by, updated_by } = row;
        const userFields = ['id', 'username', 'name', 'phone', 'avatar', 'email', 'avatar', 'gender', 'birthday', 'user_type', 'status', 'last_login_time', 'last_login_ip'];
        const SQL = `
            SELECT 
                ${userFields.join(', ')}
            FROM 
                system_users 
            WHERE 
                id IN ('${created_by}', '${updated_by}') 
            AND is_delete = 0
        `;
        const result = await db.query(SQL);
        // 如果没有查询到用户信息
        if (result.code !== 200 || result.results.length === 0) {
            row[created_key] = null;
            row[updated_key] = null;
            return row;
        }
        const create_user = result.results.find(u => u.id === created_by);
        const update_user = result.results.find(u => u.id === updated_by);

        // 如果不需要字段，则直接返回用户明恒
        if (!fields) {
            row[created_key] = create_user ? create_user.name : null;
            row[updated_key] = update_user ? update_user.name : null;
            return row;
        }

        // 如果需要自定义字段
        const userData = Array.isArray(fields) ? fields.reduce((result, key) => {
            if (!userFields.includes(key)) return result;
            if (create_user) {
                result[created_key][key] = create_user[key]
            }
            if (update_user) {
                result[updated_key][key] = update_user[key]
            }
            return result;

        }, {
            [created_key]: {},
            [updated_key]: {}
        }) : {};
        row = { ...row, ...userData }
        return row;
    }

    /**
     * 设置列表行用户
     * @param {*} param0 
     * @returns 
     */
    async setListRowUser({ list, fields, created_key, updated_key }) {
        try {
            if (!list) return list;
            created_key = created_key || 'created_user';
            updated_key = updated_key || 'updated_user';
            const userIds = [];
            const userMap = {};
            for (let i = 0, len = list.length; i < len; i++) {
                const { created_by, updated_by } = list[i];
                if (!userIds.includes(created_by)) {
                    userIds.push(created_by)
                }
                if (!userIds.includes(updated_by)) {
                    userIds.push(updated_by)
                }
            };
            const userFields = ['id', 'username', 'name', 'phone', 'avatar', 'email', 'avatar', 'gender', 'birthday', 'user_type', 'status', 'last_login_time', 'last_login_ip'];
            const SQL = `
                SELECT 
                    ${userFields.join(', ')}
                FROM 
                    system_users 
                WHERE 
                    id IN (${userIds.map(i => `'${i}'`).join(', ')}) 
                AND is_delete = 0
            `;
            const result = await db.query(SQL);
            // 如果没有查询到用户信息
            if (result.code !== 200 || result.results.length === 0) {
                return list;
            }

            // 组装成map
            result.results.forEach(user => {
                userMap[user.id] = user;
            });
            const mergeResults = [];
            // 遍历列表组装用户字段
            list.forEach(row => {
                const create_user = userMap[row.created_by];
                const update_user = userMap[row.updated_by];

                // 如果不需要字段，则直接返回用户明恒
                if (!fields) {
                    row[created_key] = create_user ? create_user.name : null;
                    row[updated_key] = update_user ? update_user.name : null;
                    mergeResults.push(row);
                    return;
                }

                // 如果需要自定义字段
                const userData = Array.isArray(fields) ? fields.reduce((result, key) => {
                    if (!userFields.includes(key)) return result;
                    if (create_user) {
                        result[created_key][key] = create_user[key]
                    }
                    if (update_user) {
                        result[updated_key][key] = update_user[key]
                    }
                    return result;

                }, {
                    [created_key]: {},
                    [updated_key]: {}
                }) : {};
                mergeResults.push({ ...row, ...userData })
            });
            
            return mergeResults;
        } catch (error) {
            console.log('setListRowUser error：', error);
            return list;
        }
    }
}

module.exports = CommonService;